package hhm.android.main

import android.text.Html
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.app.hubert.guide.NewbieGuide
import com.app.hubert.guide.model.GuidePage
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import hhm.android.library.calendarView.Calendar
import hhm.android.library.calendarView.CalendarView
import hhm.android.library.utils.BackListener
import hhm.android.library.utils.OnMultiClickListener
import siau.android.base.*
import siau.android.http.model.*
import siau.android.library.KeyString
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap

class OneFragmentToothBrushInner() : OneFragmentInner() {

    constructor(hasOut: Boolean, outShow: Boolean) : this() {
        isHasOut = hasOut
        isOutShow = outShow
    }

    private lateinit var recycler: RecyclerView
    private lateinit var buy: TextView
    private lateinit var topIv: ImageView
    private lateinit var dayLeftIv: ImageView
    private lateinit var leftMonth: ImageView
    private lateinit var nextMonth: ImageView
    private lateinit var topTv: TextView
    private lateinit var add: TextView
    private lateinit var dayLeft: TextView
    private lateinit var dayText: TextView
    private lateinit var reset: TextView
    private lateinit var backToday: TextView
    private lateinit var dateNow: TextView
    private lateinit var timeTip: TextView
    private lateinit var changeText: TextView
    private lateinit var connectState: TextView
    private lateinit var dayLeftLine: View
    private lateinit var blueToothLl: LinearLayout
    private lateinit var timeRl: RelativeLayout
    private lateinit var smart: SmartRefreshLayout
    private lateinit var buyCl: ConstraintLayout
    private lateinit var calendarCl: ConstraintLayout
    private lateinit var resetCl: ConstraintLayout
    private lateinit var calendarView: CalendarView
    private var childAdapter: ChildAdapter? = null
    private var startYear: Int = 0
    private var startMonth: Int = 0
    private var initCalendar = true
    private var refreshCalendarHttp = false

    private var bindDevice: MutableLiveData<DeviceModel> = MutableLiveData()
    private lateinit var calendarDate: String

    override fun getContentViewId(): Int {
        return R.layout.fragment_one_fragment_tooth_brush_inner
    }

    override fun initView(view: View?) {
        smart = view?.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_smart)!!
        recycler = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_recycler)!!

        //未连接设备
        buy = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_buy)!!

        add = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_start_add)!!
        topIv = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_top_iv)!!
        topTv = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_top_tv)!!
        buyCl = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_buy_cl)!!

        //已连接设备
        dayLeft = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_day_left)!!
        dayText = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_day)!!
        dayLeftIv = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_day_left_iv)!!
        connectState = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_connect_state)!!
        reset = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_reset)!!
        changeText = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_change_text)!!
        leftMonth = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_calendar_left_month)!!
        nextMonth = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_calendar_next_month)!!
        dateNow = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_calendar_date_now)!!
        backToday = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_calendar_back_today)!!
        calendarView = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_calendar_calendarView)!!

        timeTip = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_time_tip)!!
        timeRl = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_time_rl)!!
        dayLeftLine = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_day_left_line)!!
        blueToothLl = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_bluetooth_ll)!!
        resetCl = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_reset_cl)!!
        calendarCl = view.findViewById(R.id.fragment_one_fragment_tooth_brush_inner_calendar_cl)!!

        val sdf = SimpleDateFormat("yyyy-MM")
        calendarDate = sdf.format(Date())
        changeText.text = Html.fromHtml("<div style='color:#333333'>宝宝的牙刷头已经使用<font color='#FF4E4E'>90天</font>了哦！为了宝宝的<font color='#FF4E4E'>牙齿健康</font>，请及时<font color='#FF4E4E'>更换刷头</font>哦～</div>")

        bindDevice.observe(this, {
            if (it != null) {
                timeTip.visibility = View.VISIBLE
                timeRl.visibility = View.VISIBLE
                dayLeftLine.visibility = View.VISIBLE
                blueToothLl.visibility = View.VISIBLE
//                resetCl.visibility = View.VISIBLE
                calendarCl.visibility = View.VISIBLE
                add.visibility = View.GONE
                topIv.visibility = View.GONE
                topTv.visibility = View.GONE
                buyCl.visibility = View.GONE

            } else {
                timeTip.visibility = View.GONE
                timeRl.visibility = View.GONE
                dayLeftLine.visibility = View.GONE
                blueToothLl.visibility = View.GONE
                resetCl.visibility = View.GONE
                calendarCl.visibility = View.GONE
                add.visibility = View.VISIBLE
                topIv.visibility = View.VISIBLE
                topTv.visibility = View.VISIBLE
                buyCl.visibility = View.VISIBLE
            }
        })

        SBApplication.getBlueToothUtils().scanDevicesNum.observe(this, {
            if (bindDevice != null) {
                refreshConnectState()
            }
        })

        initChildren()
    }

    private fun getSchemeCalendar(year: Int, month: Int, day: Int, scheme: String): Calendar {
        val calendar = Calendar()
        calendar.year = year
        calendar.month = month
        calendar.day = day
        calendar.scheme = scheme
        return calendar
    }

    /**
     * boolean值 留的口子 用来保留之前选择的孩子 新增加孩子的时候 跳转页面之前选了第n个孩子 加入boolean值，
     * 就能在孩子列表刷新之后指向对应的孩子，否则孩子列表一旦刷新，只能默认指向第一个孩子
     */
    private fun initChildren() {
        list = ArrayList()

        val lm = LinearLayoutManager(activity)
        lm.orientation = LinearLayoutManager.HORIZONTAL
        recycler.layoutManager = lm

        childAdapter = activity?.let {
            ChildAdapter(it, list, { i ->
                initCalendar = true
                val sdf = SimpleDateFormat("yyyy-MM")
                calendarDate = sdf.format(Date())
                childIdNow = list[i].childId
                SBApplication.communityChildId = childIdNow
                childAdapter?.notifyDataSetChanged()
                getData()
            }, object : BackListener {
                override fun callBack() {
                    ARouter.getInstance().build(BABY_ROUTE).withInt(KeyString.type, 0).navigation()
                }
            })
        }!!
        recycler.adapter = childAdapter
    }

    override fun initData() {
        super.initData()
    }

    override fun getData() {
        HttpHelper().myBabyList()?.subscribe({

            list.clear()
            list.addAll(it)
            SBApplication.userData.children = it
            var has = false
            list.forEach { i ->
                if (i.childId == childIdNow && i.childId != -1) {
                    i.select = true
                    SBApplication.communityChildId = i.childId
                    has = true
                    bindDevice.value = null
                    SBApplication.userData.deviceList?.forEach { device ->
                        if (device.relationType == 2 && device.childId == childIdNow) {
                            bindDevice.value = device
                        }
                    }
                }
            }
            if (!has && list.size > 0) {
                list[0].select = true
                initCalendar = true
                val sdf = SimpleDateFormat("yyyy-MM")
                calendarDate = sdf.format(Date())
                SBApplication.communityChildId = list[0].childId
                childIdNow = list[0].childId
                bindDevice.value = null
                SBApplication.userData.deviceList?.forEach { device ->
                    if (device.relationType == 2 && device.childId == childIdNow) {
                        bindDevice.value = device
                    }
                }
            }

            if (SBApplication.userData.isCreator == 1) {
                val c = ChildModel(-1, "", "", false, -1, 0, 0, -1.0, -1.0)
                list.add(c)
            }

            childAdapter?.setData(list)
            smart.finishRefresh()

            if (childIdNow == -1) {
                return@subscribe
            }

            if (bindDevice.value != null) {
                getBluetoothData()
            }

        }, {
            smart.finishRefresh()
            removeLoadingFragment()
            showToast(it.message)
        })

        //转让家庭之后去掉加号
        if (SBApplication.userData.isCreator != 1 && list.size > 0 && list[list.size - 1].childId == -1) {
            list.removeAt(list.size - 1)
            childAdapter?.notifyDataSetChanged()
        }
    }

    private fun getBluetoothData() {
        refreshConnectState()

        val request = bindDevice.value?.bluetoothCode?.let { BluetoothCodeRequest(it) }
        if (request != null) {
            HttpHelper().getRemainingTime(request)?.subscribe({
                if (it.promptStatus == 1) {
                    activity?.let { a ->
                        getChangeToothBrushHeadDialog(a, object : OnMultiClickListener() {
                            override fun onMultiClick(v: View?) {

                            }
                        })
                    }
                }
                when {
                    it.remainingTime <= 7 -> {
                        dayLeft.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_FF4E4E))
                        dayText.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_FF4E4E))
                        dayLeftIv.setImageResource(R.mipmap.tooth_brush_state_red)
                    }
                    it.remainingTime <= 30 -> {
                        dayLeft.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_FFDF5D))
                        dayText.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_FFDF5D))
                        dayLeftIv.setImageResource(R.mipmap.tooth_brush_state_yellow)
                    }
                    else -> {
                        dayLeft.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_A7E5B4))
                        dayText.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_A7E5B4))
                        dayLeftIv.setImageResource(R.mipmap.tooth_brush_state_green)
                    }
                }
                dayLeft.text = it.remainingTime.toString()

                if (it.remainingTime == 0) {
                    resetCl.visibility = View.VISIBLE
                } else {
                    resetCl.visibility = View.GONE
                }
            }, {
                showToast(it.message)
            })
        }

        getBrushList()
    }

    private fun getBrushList() {
        val r = GetBrushListRequest(bindDevice.value!!.bluetoothCode, calendarDate)
        HttpHelper().getBrushList(r)?.subscribe({
            setBrushListData(it)
        }, {
            showToast(it.message)
        })
    }

    private fun setBrushListData(it: GetBrushListResponse) {
        if (initCalendar) {
            initCalendar = false

            refreshCalendarHttp = false
            calendarView.scrollToCurrent()

            val curYear = calendarView.curYear
            val curMonth = calendarView.curMonth

            if (!TextUtils.isEmpty(it.startTime)) {
                val split = it.startTime.split("-")
                startYear = split[0].toInt()
                startMonth = split[1].toInt()

                if (curYear > startYear || (curYear == startYear && curMonth > startMonth)) {
                    leftMonth.setImageResource(R.mipmap.calendar_left_arrow_can)
                    leftMonth.isEnabled = true
                } else {
                    leftMonth.setImageResource(R.mipmap.calendar_left_arrow_can_not)
                    leftMonth.isEnabled = false
                }
            } else {
                startYear = calendarView.curYear
                startMonth = calendarView.curMonth
                leftMonth.setImageResource(R.mipmap.calendar_left_arrow_can_not)
                leftMonth.isEnabled = false
            }

            nextMonth.setImageResource(R.mipmap.calendar_right_arrow_can_not)
            nextMonth.isEnabled = false
            dateNow.text = "${curYear}年${curMonth}月"

            leftMonth.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    refreshCalendarHttp = true
                    calendarView.scrollToPre()
                }
            })
            nextMonth.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    refreshCalendarHttp = true
                    calendarView.scrollToNext()
                }
            })
            backToday.setOnClickListener(object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    refreshCalendarHttp = true
                    calendarView.scrollToCurrent()
                }
            })
            calendarView.setOnMonthChangeListener { year, month ->
                if (year > startYear || (year == startYear && month > startMonth)) {
                    leftMonth.setImageResource(R.mipmap.calendar_left_arrow_can)
                    leftMonth.isEnabled = true
                } else {
                    leftMonth.setImageResource(R.mipmap.calendar_left_arrow_can_not)
                    leftMonth.isEnabled = false
                }
                if (curYear > year || (curYear == year && curMonth > month)) {
                    nextMonth.setImageResource(R.mipmap.calendar_right_arrow_can)
                    nextMonth.isEnabled = true
                } else {
                    nextMonth.setImageResource(R.mipmap.calendar_right_arrow_can_not)
                    nextMonth.isEnabled = false
                }
                dateNow.text = "${year}年${month}月"
                if (month < 10) {
                    calendarDate = "${year}-0${month}"
                } else {
                    calendarDate = "${year}-${month}"
                }
                if (refreshCalendarHttp) {
                    getBrushList()
                } else {
                    refreshCalendarHttp = true
                }
            }
        }

        calendarView.clearSchemeDate()
        val map: MutableMap<String, Calendar> = HashMap()
        if (it.list != null && it.list.size > 0) {
            it.list.forEach { getBrushListModel ->
                val split = getBrushListModel.brushDate.split("-")
                map[getSchemeCalendar(split[0].toInt(), split[1].toInt(), split[2].toInt(), getBrushListModel.starStatus.toString()).toString()] = getSchemeCalendar(split[0].toInt(), split[1].toInt(), split[2].toInt(), getBrushListModel.starStatus.toString())
            }
        }

        //此方法在巨大的数据量上不影响遍历性能，推荐使用
        calendarView.setSchemeDate(map)

        if (SBApplication.userData.toothBrushGuide == 1) {

            SBApplication.userData.toothBrushGuide = 0

            NewbieGuide.with(this).setLabel("guide_toothbrush").alwaysShow(true).addGuidePage(
                GuidePage.newInstance().addHighLight(calendarCl).setLayoutRes(R.layout.guide_toothbrush)
            ).show()
        }
    }

    override fun initEvent() {
        buy.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                if (SystemUtil.isPkgInstalled(activity, "com.taobao.taobao")) {
                    SystemUtil.gotoShop(activity, "taobao://shop504445296.m.taobao.com")
                } else {
                    showToast("您还没有安装淘宝客户端！")
                }
            }
        })
        add.setOnClickListener {
            ARouter.getInstance().build(MACHINE_ROUTER).navigation()
        }

        smart.setEnableLoadMore(false)
        smart.setOnRefreshListener {
            getData()
        }
    }

    private fun refreshConnectState() {
        var hasConnect = false
        SBApplication.getBlueToothUtils().connectDevice.forEach {
            if (it.bluetoothCode == bindDevice.value?.bluetoothCode) {
                hasConnect = true
            }
        }
        if (hasConnect) {
            connectState.text = "已连接"
            connectState.setTextColor(ContextCompat.getColor(requireActivity(), R.color.mainTextColor))
        } else {
            connectState.text = "未连接"
            connectState.setTextColor(ContextCompat.getColor(requireActivity(), R.color.color_666666))
        }
    }

    override fun selectSomeChild(childId: Int) {
        childIdNow = childId
        list.forEach { i ->
            i.select = i.childId == childIdNow
        }
        childAdapter?.notifyDataSetChanged()
        getData()
    }
}